package iputils

import (
	"boy-go/pkg/config"
	"boy-go/pkg/constants"
	"boy-go/pkg/xhttp"
	"github.com/gin-gonic/gin"
	"github.com/goccy/go-json"
	"net"
)

var (
	IP_URL = "http://whois.pconline.com.cn/ipJson.jsp"
)

func getClientIPv4(c *gin.Context) string {
	ipStr := c.ClientIP()
	ip := net.ParseIP(ipStr)
	if ip4 := ip.To4(); ip4 != nil {
		return ip4.String()
	}
	return "127.0.0.1"
}

func GetIp(c *gin.Context) string {
	return getClientIPv4(c)
}

func GetRealAddressByIP(ip string) string {
	if InternalIp(ip) {
		return "内网IP"
	}
	if config.GetBoyGoConfig().AddressEnabled == true {
		param := "ip=" + ip + "&json=true"
		rspStr := xhttp.SendGet(IP_URL, &param, &constants.GBK)
		if rspStr != "" {
			obj := make(map[string]interface{}, 0)
			err := json.Unmarshal([]byte(rspStr), &obj)
			if err == nil {
				region, _ := obj["pro"]
				city, _ := obj["city"]
				res := region.(string) + " " + city.(string)
				return res
			}
		}
	}
	return "XX XX"
}

func InternalIp(ip string) bool {
	return isPrivateIP(ip) || ip == "127.0.0.1" || ip == "::1"
}
func isPrivateIP(ipStr string) bool {
	ip := net.ParseIP(ipStr)
	_, private10BitNet, _ := net.ParseCIDR("10.0.0.0/8")
	_, private172BitNet, _ := net.ParseCIDR("172.16.0.0/12")
	_, private192BitNet, _ := net.ParseCIDR("192.168.0.0/16")
	_, loopBackBitNet, _ := net.ParseCIDR("127.0.0.0/8")
	return private10BitNet.Contains(ip) || private172BitNet.Contains(ip) || private192BitNet.Contains(ip) || loopBackBitNet.Contains(ip)
}
